﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SAUlot
{
    public class AirplaneControler
    {
        private ManualResetEvent endEvent;
        private Thread airplaneThread;
        private AirplaneModel airplaneModel;

        private double[] steering;
        private int counter;

        public AirplaneControler()
        {
            steering = new double[1];
            counter = 0;
        }

        public AirplaneModel Model
        {
            get { return airplaneModel; }
            set { airplaneModel = value; }
        }

        private AirplaneView airplaneView;
        public AirplaneView View
        {
            get { return airplaneView; }
            set { 
                airplaneView = value; 
                airplaneModel.CCMoveEvent += new Reinforcement.CCActionHandler(airplaneView.UpdateState); 
            }
        }
        //private AktorKrytyk krytyk;

        public void StartThread()
        {
            airplaneThread = new Thread(new ThreadStart(Actualize));
            airplaneThread.Start();
        }

        public void EndThread()
        {
            if (airplaneThread != null)
            {
                endEvent.Set();
                airplaneThread.Join();
            }
        }

        //metoda do wywołania w wątku
        public void Actualize()
        {
            endEvent = new ManualResetEvent(false);
            while (true)
            {
                if (endEvent != null && endEvent.WaitOne(0, false))
                    return;

                //invokniecie delegata z modelu co by poobliczał, albo po prostu metode, wypadaloby jakies mutexy walnac w modelu dla czystosci, ale nie musi byc
                if (counter-- == 0)
                {
                    steering[0] = new Random().NextDouble() - 0.5;
                    counter = 100;
                }
                airplaneModel.CCMove(steering);
                Thread.Sleep(20);
            }
        }
        public void Reset()
        {
            airplaneModel.CCStartInRandomState();
        }
    }
}
